<?php

/**
 * ECSHOP 代理商管理程序
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: goods.php 17217 2011-01-19 06:29:08Z liubo $
 */

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');

$exc = new exchange($ecs->table("recommend"), $db, 'recommend_id', 'recommend_name');

if ($_REQUEST['act'] == 'list')
{
    $recommend = array();
    $recommend = $db->getAll("SELECT * FROM " .$ecs->table('recommend'));

    //$recommend_count =$db->getone("SELECT count(*) FROM " .$ecs->table('recommend'));

    $smarty->assign('ur_here',      $_LANG['02_recommend_list']);
    //$smarty->assign('action_link',  array('text' => $_LANG['add_user_rank'], 'href'=>'user_rank.php?act=add'));
    $smarty->assign('full_page',    1);
   // $smarty->assign('recommend',   $recommend);

    $recommend_list = get_recommend_list();

    $smarty->assign('recommend',    $recommend_list['arr']);

    $smarty->assign('action_link',      array('text' => $_LANG['03_recommend_tier'], 'href'=>'recommend.php?act=tier'));
    $smarty->assign('filter',          $recommend_list['filter']);
    $smarty->assign('record_count',    $recommend_list['record_count']);
    $smarty->assign('page_count',      $recommend_list['page_count']);

    assign_query_info();
    $smarty->display('recommend_list.htm');
}


elseif ($_REQUEST['act'] == 'tier')
{
    $sql = "select c.recommend_id,c.recommend_name,c.recommend_parent_id,c.recommend_agency_rank,count(s.recommend_id) from ".$GLOBALS['ecs']->table('recommend')." as c "."left join ".$GLOBALS['ecs']->table('recommend')." as s on s.recommend_parent_id=c.recommend_id "."group by c.recommend_id "."order by c.recommend_parent_id asc";
    $listarr = $GLOBALS['db']->getAll($sql);

    //首先遍历根节点并根据根节点查找到所有子节点
    $tr = '';
    for($i=0;$i<count($listarr);$i++){
        $low = 0;
        $hight =count($listarr)-1;
        if($listarr[$i]['recommend_parent_id']==0){
            $tr .= "<tr class='".($listarr[$i]['recommend_agency_rank']-1)."' id='".($listarr[$i]['recommend_agency_rank']-1)."_".$listarr[$i]['recommend_id']."'><td ".
//             value='".$listarr[$i]['recommend_id']."'
             "><img src='images/menu_minus.gif' id='icon_".($listarr[$i]['recommend_agency_rank']-1)."_".$listarr[$i]['recommend_id']."' width='9' height='9' border='0' style='margin-left:".$listarr[$i]['recommend_agency_rank']."em' onclick='rowClicked(this)'/>
             <span style='font-size:12px;font-weight:bold;color:#9cacaf'>".$listarr[$i]['recommend_agency_rank']."级代理商--</span>"."<span style='font-size:12px;font-weight:bold'>"
.$listarr[$i]['recommend_name']."</span>
             <span style='margin-left:88px'>
             <a href='recommend.php?act=move&recommend_id=".$listarr[$i]['recommend_id']."'>转移代理商</a> |
             <a href='users.php?act=edit&id=".$listarr[$i]['recommend_id']."&type=recommend'>编辑</a> |

             <a title='移除' onclick='listTable.remove(".$listarr[$i]['recommend_id'].",\"你确定要删除这条记录吗？\")' href='javascript:;'>移除</a>


             </span>
             </td></tr>";

       /*     <a href="javascript:;" onclick="listTable.remove({$cat.cat_id}, '{$lang.drop_confirm}')" title="{$lang.remove}">{$lang.remove}</a>
       <a title='移除' onclick='listTable.remove(".$listarr[$i]['recommend_id'].", '"."你确定要删除这条记录吗？"."')' href='javascript:;'>移除</a>
       */

            $tr .=getSelectChild($listarr,$listarr[$i]['recommend_id'],$low,$hight);
        }else{
            break;
        }
    }

    $smarty->assign('tr',$tr);
    $smarty->assign('ur_here',     $_LANG['03_recommend_tier']);
    $smarty->assign('action_link',      array('text' => $_LANG['02_recommend_list'], 'href'=>'recommend.php?act=list'));

    $smarty->assign('full_page',   1);

    assign_query_info();
    $smarty->display('recommend_tier.htm');
}

elseif ($_REQUEST['act'] == 'remove')
{
    $id=$_REQUEST['id'];
    $sql = "select recommend_id from ".$ecs->table('recommend')." where recommend_parent_id = ".$id;
    $recommend_id=$db->getRow($sql);
   // echo 0;

    if($recommend_id['recommend_id']!=''){
        //echo 1;
        make_json_error("此代理商下有下级代理商，请先转移下级代理商！");

        //sys_msg("此代理商下有下级代理商，请先转移下级代理商！");
    }else{
       // echo 2;
        $sql = "delete from ".$ecs->table('recommend')." where recommend_id = ".$id;
        $db->query($sql);
        /* 移除后用户变为非特殊等级 */
        $sql2 = "update ".$ecs->table('users')." set user_rank=0 where user_id=".$id;
        $db->query($sql2);
        //sys_msg('删除成功！', 0);
    }
    $url = 'recommend.php?act=query_tier&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    ecs_header("Location: $url\n");


    exit;

}

elseif ($_REQUEST['act'] == 'query_tier')
{
    $sql = "select c.recommend_id,c.recommend_name,c.recommend_parent_id,c.recommend_agency_rank,count(s.recommend_id) from ".$GLOBALS['ecs']->table('recommend')." as c "."left join ".$GLOBALS['ecs']->table('recommend')." as s on s.recommend_parent_id=c.recommend_id "."group by c.recommend_id "."order by c.recommend_parent_id asc";
    $listarr = $GLOBALS['db']->getAll($sql);

    //首先遍历根节点并根据根节点查找到所有子节点
    $tr = '';
    for($i=0;$i<count($listarr);$i++){
        $low = 0;
        $hight =count($listarr)-1;
        if($listarr[$i]['recommend_parent_id']==0){
            $tr .= "<tr class='".($listarr[$i]['recommend_agency_rank']-1)."' id='".($listarr[$i]['recommend_agency_rank']-1)."_".$listarr[$i]['recommend_id']."'><td ".
//             value='".$listarr[$i]['recommend_id']."'
                "><img src='images/menu_minus.gif' id='icon_".($listarr[$i]['recommend_agency_rank']-1)."_".$listarr[$i]['recommend_id']."' width='9' height='9' border='0' style='margin-left:".$listarr[$i]['recommend_agency_rank']."em' onclick='rowClicked(this)'/>
             <span style='font-size:12px;font-weight:bold;color:#9cacaf'>".$listarr[$i]['recommend_agency_rank']."级代理商--</span>"."<span style='font-size:12px;font-weight:bold'>"
                .$listarr[$i]['recommend_name']."</span>
             <span style='margin-left:88px'>
             <a href='recommend.php?act=move&recommend_id=".$listarr[$i]['recommend_id']."'>转移代理商</a> |
             <a href='users.php?act=edit&id=".$listarr[$i]['recommend_id']."&type=recommend'>编辑</a> |

             <a title='移除' onclick='listTable.remove(".$listarr[$i]['recommend_id'].",\"你确定要删除这条记录吗？\")' href='javascript:;'>移除</a>


             </span>
             </td></tr>";

            /*     <a href="javascript:;" onclick="listTable.remove({$cat.cat_id}, '{$lang.drop_confirm}')" title="{$lang.remove}">{$lang.remove}</a>
            <a title='移除' onclick='listTable.remove(".$listarr[$i]['recommend_id'].", '"."你确定要删除这条记录吗？"."')' href='javascript:;'>移除</a>
            */

            $tr .=getSelectChild($listarr,$listarr[$i]['recommend_id'],$low,$hight);
        }else{
            break;
        }
    }

    $smarty->assign('tr',$tr);
    $smarty->assign('ur_here',     $_LANG['03_recommend_tier']);
    $smarty->assign('full_page',   0);

    assign_query_info();
    make_json_result($smarty->fetch('recommend_tier.htm'), '');
}



elseif ($_REQUEST['act'] == 'edit_recommend')
{
    check_authz_json('recommend');

    $recommend_id = empty($_REQUEST['id']) ? 0 : intval($_REQUEST['id']);
    $val = empty($_REQUEST['val']) ? 0 : floatval($_REQUEST['val']);

    if ($val < 0)
    {
        make_json_error('业绩不能为负数！');
    }

    if ($exc->edit("recommend_performance = '$val'", $recommend_id))
    {
        $recommend_name = $exc->get_name($recommend_id);
        //admin_log(addslashes($recommend_name), 'edit', 'user_rank');
        clear_cache_files();
        make_json_result($val);
    }
    else
    {
        make_json_error($val);
    }
}

/*------------------------------------------------------ */
//-- 排序、分页、查询
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query')
{
    $recommend_list = get_recommend_list();

    $smarty->assign('recommend',    $recommend_list['arr']);
    $smarty->assign('filter',          $recommend_list['filter']);
    $smarty->assign('record_count',    $recommend_list['record_count']);
    $smarty->assign('page_count',      $recommend_list['page_count']);
    $sort_flag  = sort_flag($recommend_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);
    make_json_result($smarty->fetch('recommend_list.htm'), '', array('filter' => $recommend_list['filter'], 'page_count' => $recommend_list['page_count']));
}

/* 移动代理商 */
elseif ($_REQUEST['act'] == 'move')
{
    $recommend_id=$_REQUEST['recommend_id'];

    $sql = "select recommend_id,recommend_agency_rank, recommend_name from ".$ecs->table('recommend')." where recommend_id=".$recommend_id;
    $rank=$db->getRow($sql);
    $smarty->assign("rank",$rank);

    $sql2 = "select recommend_agency_rank from ".$ecs->table('recommend')." group by recommend_agency_rank";
    $ranks=$db->getAll($sql2);

    $max_rank1= $db->getOne("select max(distinct recommend_agency_rank) from ".$ecs->table('recommend'));
    $max_rank2 = $max_rank1+1;

    $smarty->assign("ranks",$ranks);
    $smarty->assign('max_rank1',$max_rank1);
    $smarty->assign('max_rank2',$max_rank2);
    $smarty->assign('ur_here',     '转移代理商');
    $smarty->assign('action_link', array('href' => 'recommend.php?act=tier', 'text' => '代理商层级'));
    $smarty->display('recommend_move.htm');
}

elseif ($_REQUEST['act'] == 'move_change')
{
    $recommend_id=$_REQUEST['id'];
    $recommend_agency_rank=$_REQUEST['level']-1;

    $children=get_recommend_children($recommend_id);

    $sql = "select recommend_id, recommend_name from ".$ecs->table('recommend')." where recommend_agency_rank=".$recommend_agency_rank." and ".$children;

    $list=$db->getAll($sql);
    $options="";
    foreach($list as $k=>$v){
        $options .="<option value='".$v['recommend_id']."'>".$v['recommend_name']."</option>";
    }
    echo $options;
}

elseif ($_REQUEST['act'] == 'move_update')
{
   $old_id=$_REQUEST['recommend_id'];
   $new_rank=$_REQUEST['recommend_agency_rank'];
   $old_rank=$_REQUEST['old_rank'];
   $i=$new_rank-$old_rank;

   $parent_id=empty($_REQUEST['recommend_parent_id']) ? 0 : $_REQUEST['recommend_parent_id'];

    $sql = "update ".$ecs->table('recommend')." set recommend_parent_id=".$parent_id." where recommend_id=".$old_id;
    $db->query($sql);

    $children_arr=array_unique(array_merge(array($old_id), array_keys(recommend_cat_list($old_id, 0, false))));
    foreach($children_arr as $k=>$v){
        $sql1 = "select recommend_agency_rank from ".$ecs->table('recommend')." where recommend_id=".$v;
        $data=$db->getRow($sql1);
        $old_val = $data['recommend_agency_rank'];
        $new_val = $old_val+$i;
        $sql2 = "update ".$ecs->table('recommend')." set recommend_agency_rank=".$new_val." where recommend_id=".$v;
        $db->query($sql2);
    }
    $links[0]['href']    = 'recommend.php?act=tier';
    $links[0]['text']    = '返回代理商层级';
    $links[1]['text']    = $_LANG['go_back'];
    $links[1]['href']    = 'javascript:history.back()';

    sys_msg('修改成功！', 0, $links);
}
/* 获得代理商列表 */
function get_recommend_list()
{
    $result = get_filter();
    if ($result === false)
    {
        $filter = array();
        $filter['keyword']    = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
        $where = '';
        if (!empty($filter['keyword']))
        {
            $where = " AND recommend_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%'";
        }
        /* 代理商总数 */
        $sql = 'SELECT COUNT(*) FROM ' .$GLOBALS['ecs']->table('recommend')." where 1=1 ".$where;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);

        $filter = page_and_size($filter);

        /* 获取代理商数据 */
        $sql = 'SELECT * FROM ' .$GLOBALS['ecs']->table('recommend')." where 1=1 ".$where;

        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $arr = array();
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    while ($rows = $GLOBALS['db']->fetchRow($res))
    {
        $rows['date'] = local_date($GLOBALS['_CFG']['time_format'], $rows['add_time']);

        $arr[] = $rows;
    }
    return array('arr' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}

/* 二分法分类 */

function getSelectChild($listarr,$pid,$low,$hight){
    $tr = '';
    $mid =intval(($low+$hight)/2);
    while($hight>=$low){
        $mid =intval(($low+$hight)/2);
        if($pid > $listarr[$mid]['recommend_parent_id']){//父id大于中间值 向下查
            $low = $mid+1;
        }else if($pid < $listarr[$mid]['recommend_parent_id']){//  父id小于中间值 向上查找
            $hight = $mid-1;
        }else if($pid == $listarr[$mid]['recommend_parent_id']){//  父id等于于中间值 即向上查找 又得向下查找
            $n = $listarr[$mid]['recommend_agency_rank']; //按’，‘统计层次数

            $h =  str_repeat("",$n-1)."<img src='images/menu_minus.gif' id='icon_".($listarr[$mid]['recommend_agency_rank']-1)."_".$listarr[$mid]['recommend_id']."' width='9' height='9' border='0' style='margin-left:".$listarr[$mid]['recommend_agency_rank']."em' onclick='rowClicked(this)'/>";

            $tr .= "<tr class='".($listarr[$mid]['recommend_agency_rank']-1)."' id='".($listarr[$mid]['recommend_agency_rank']-1)."_".$listarr[$mid]['recommend_id']."'><td ".
//            value='".$listarr[$mid]['recommend_id']."'
           " >".$h."<span style='font-size:12px;font-weight:bold;color:#9cacaf'>&nbsp;&nbsp;".$listarr[$mid]['recommend_agency_rank']."级代理商--</span>"."<span style='font-size:12px;font-weight:bold'>"
                .$listarr[$mid]['recommend_name']."</span>
           <span style='margin-left:88px'><a href='recommend.php?act=move&recommend_id=".$listarr[$mid]['recommend_id']."'>转移代理商</a> | <a href='users.php?act=edit&id=".$listarr[$mid]['recommend_id']."&type=recommend'>编辑</a> |

           <a title='移除' onclick='listTable.remove(".$listarr[$mid]['recommend_id'].",\"你确定要删除这条记录吗？\")' href='javascript:;'>移除</a>
           </span>
           </td></tr>";
            $tr .= getSelectChild($listarr,$listarr[$mid]['recommend_id'],0,count($listarr)-1);

            if(($mid+1) < count($listarr)){
                if($pid == $listarr[$mid+1]['recommend_parent_id']){//当下一个数组的父id等于所有查找的pid时遍历出下面数组中所有等于pid的数组

                    for($i=$mid+1;$i<=$hight;$i++){
                        if($pid==$listarr[$i]['recommend_parent_id']){
                            $n = $listarr[$mid]['recommend_agency_rank']; //按’，‘统计层次数
                            $h =  str_repeat("",$n-1)."<img src='images/menu_minus.gif' id='icon_".($listarr[$i]['recommend_agency_rank']-1)."_".$listarr[$i]['recommend_id']."' width='9' height='9' border='0' style='margin-left:".$listarr[$i]['recommend_agency_rank']."em' onclick='rowClicked(this)'/>";
                            $tr .= "<tr class='".($listarr[$i]['recommend_agency_rank']-1)."' id='".($listarr[$i]['recommend_agency_rank']-1)."_".$listarr[$i]['recommend_id']."'><td ".
//                            value='".$listarr[$i]['recommend_id']."'
                            ">".$h."<span style='font-size:12px;font-weight:bold;color:#9cacaf'>&nbsp;&nbsp;".$listarr[$i]['recommend_agency_rank']."级代理商--</span>"."<span style='font-size:12px;font-weight:bold'>"
                                .$listarr[$i]['recommend_name']."</span>
                            <span style='margin-left:88px'><a href='recommend.php?act=move&recommend_id=".$listarr[$i]['recommend_id']."'>转移代理商</a> | <a href='users.php?act=edit&id=".$listarr[$i]['recommend_id']."&type=recommend'>编辑</a> |

                            <a title='移除' onclick='listTable.remove(".$listarr[$i]['recommend_id'].",\"你确定要删除这条记录吗？\")' href='javascript:;'>移除</a>
                            </span>
                            </td></tr>";
                            $tr .= getSelectChild($listarr,$listarr[$i]['recommend_id'],0,count($listarr)-1);
                        }
                        else{
                            break;
                        }
                    }
                }
                if($pid == $listarr[$mid-1]['recommend_parent_id']){ //当上一个数组的父id等于所有查找的pid时遍历出上面数组中所有等于pid的数组
                    for($i=$mid-1;$i>=$low;$i--){
                        if($pid==$listarr[$i]['recommend_parent_id']){
                            $n =$listarr[$mid]['recommend_agency_rank']; //按’，‘统计层次数
                            $h =  str_repeat("",$n-1)."<img src='images/menu_minus.gif' id='icon_".($listarr[$i]['recommend_agency_rank']-1)."_".$listarr[$i]['recommend_id']."' width='9' height='9' border='0' style='margin-left:".$listarr[$i]['recommend_agency_rank']."em' onclick='rowClicked(this)'/>";
                            $tr .= "<tr class='".($listarr[$i]['recommend_agency_rank']-1)."' id='".($listarr[$i]['recommend_agency_rank']-1)."_".$listarr[$i]['recommend_id']."'><td ".
//                            value='".$listarr[$i]['recommend_id']."'
                            ">".$h."<span style='font-size:12px;font-weight:bold;color:#9cacaf'>&nbsp;&nbsp;".$listarr[$i]['recommend_agency_rank']."级代理商--</span>"."<span style='font-size:12px;font-weight:bold'>"
                                .$listarr[$i]['recommend_name']."</span>
                            <span style='margin-left:88px'><a href='recommend.php?act=move&recommend_id=".$listarr[$i]['recommend_id']."'>转移代理商</a> | <a href='users.php?act=edit&id=".$listarr[$i]['recommend_id']."&type=recommend'>编辑</a> |

                            <a title='移除' onclick='listTable.remove(".$listarr[$i]['recommend_id'].",\"你确定要删除这条记录吗？\")' href='javascript:;'>移除</a>
                            </span>
                            </td></tr>";
                            $tr .= getSelectChild($listarr,$listarr[$i]['recommend_id'],0,count($listarr)-1);
                        }
                        else{
                            break;
                        }
                    }
                }
            }

            return $tr;

        }

    }

}


/**
 * 获得指定分类下所有底层分类的ID
 *
 * @access  public
 * @param   integer     $cat        指定的分类ID
 * @return  string
 */
function get_recommend_children($cat = 0)
{
    return 'recommend_id ' . recommend_db_create_in(array_unique(array_merge(array($cat), array_keys(recommend_cat_list($cat, 0, false)))));
}

    /**
     * 创建像这样的查询: "IN('a','b')";
     *
     * @access   public
     * @param    mix      $item_list      列表数组或字符串
     * @param    string   $field_name     字段名称
     *
     * @return   void
     */
    function recommend_db_create_in($item_list, $field_name = '')
    {
        if (empty($item_list))
        {
            return $field_name . " not IN ('') ";
        }
        else
        {
            if (!is_array($item_list))
            {
                $item_list = explode(',', $item_list);
            }
            $item_list = array_unique($item_list);
            $item_list_tmp = '';
            foreach ($item_list AS $item)
            {
                if ($item !== '')
                {
                    $item_list_tmp .= $item_list_tmp ? ",'$item'" : "'$item'";
                }
            }
            if (empty($item_list_tmp))
            {
                return $field_name . " not IN ('') ";
            }
            else
            {
                return $field_name . ' not IN (' . $item_list_tmp . ') ';
            }
        }
    }
/**
 * 获得指定分类下的子分类的数组
 *
 * @access  public
 * @param   int     $cat_id     分类的ID
 * @param   int     $selected   当前选中分类的ID
 * @param   boolean $re_type    返回的类型: 值为真时返回下拉列表,否则返回数组
 * @param   int     $level      限定返回的级数。为0时返回所有级数
 * @param   int     $is_show_all 如果为true显示所有分类，如果为false隐藏不可见分类。
 * @return  mix
 */
function recommend_cat_list($cat_id = 0, $selected = 0, $re_type = false)
{
    static $res = NULL;

    if ($res === NULL)
    {
            $sql = "SELECT c.recommend_id, c.recommend_name, c.recommend_parent_id, COUNT(s.recommend_id) AS has_children ".
                'FROM ' . $GLOBALS['ecs']->table('recommend') . " AS c ".
                "LEFT JOIN " . $GLOBALS['ecs']->table('recommend') . " AS s ON s.recommend_parent_id=c.recommend_id ".
                "GROUP BY c.recommend_id ".
                'ORDER BY c.recommend_parent_id ASC';

            $res = $GLOBALS['db']->getAll($sql);

    }

    if (empty($res) == true)
    {
        return $re_type ? '' : array();
    }

    $options = recommend_cat_options($cat_id, $res); // 获得指定分类下的子分类的数组

    if ($re_type == false)
    {
        return $options;
    }

}

/**
 * 过滤和排序所有分类，返回一个带有缩进级别的数组
 *
 * @access  private
 * @param   int     $cat_id     上级分类ID
 * @param   array   $arr        含有所有分类的数组
 * @param   int     $level      级别
 * @return  void
 */
function recommend_cat_options($spec_cat_id, $arr)
{

    static $cat_options = array();

    if (isset($cat_options[$spec_cat_id]))
    {
        return $cat_options[$spec_cat_id];
    }

    if (!isset($cat_options[0]))
    {
        $level = $last_cat_id = 0;
        $options = $cat_id_array = $level_array = array();

            while (!empty($arr))
            {
                foreach ($arr AS $key => $value)
                {
                    $cat_id = $value['recommend_id'];
                    if ($level == 0 && $last_cat_id == 0)
                    {
                        if ($value['recommend_parent_id'] > 0)
                        {
                            break;
                        }

                        $options[$cat_id]          = $value;
                        $options[$cat_id]['level'] = $level;
                        $options[$cat_id]['id']    = $cat_id;
                        $options[$cat_id]['name']  = $value['recommend_name'];
                        unset($arr[$key]);

                        if ($value['has_children'] == 0)
                        {
                            continue;
                        }
                        $last_cat_id  = $cat_id;
                        $cat_id_array = array($cat_id);
                        $level_array[$last_cat_id] = ++$level;
                        continue;
                    }

                    if ($value['recommend_parent_id'] == $last_cat_id)
                    {
                        $options[$cat_id]          = $value;
                        $options[$cat_id]['level'] = $level;
                        $options[$cat_id]['id']    = $cat_id;
                        $options[$cat_id]['name']  = $value['recommend_name'];
                        unset($arr[$key]);

                        if ($value['has_children'] > 0)
                        {
                            if (end($cat_id_array) != $last_cat_id)
                            {
                                $cat_id_array[] = $last_cat_id;
                            }
                            $last_cat_id    = $cat_id;
                            $cat_id_array[] = $cat_id;
                            $level_array[$last_cat_id] = ++$level;
                        }
                    }
                    elseif ($value['recommend_parent_id'] > $last_cat_id)
                    {
                        break;
                    }
                }

                $count = count($cat_id_array);
                if ($count > 1)
                {
                    $last_cat_id = array_pop($cat_id_array);
                }
                elseif ($count == 1)
                {
                    if ($last_cat_id != end($cat_id_array))
                    {
                        $last_cat_id = end($cat_id_array);
                    }
                    else
                    {
                        $level = 0;
                        $last_cat_id = 0;
                        $cat_id_array = array();
                        continue;
                    }
                }

                if ($last_cat_id && isset($level_array[$last_cat_id]))
                {
                    $level = $level_array[$last_cat_id];
                }
                else
                {
                    $level = 0;
                }
            }
            //如果数组过大，不采用静态缓存方式

        $cat_options[0] = $options;
    }
    else
    {
        $options = $cat_options[0];
    }


    if (!$spec_cat_id)
    {
        return $options;
    }
    else
    {
        if (empty($options[$spec_cat_id]))
        {
            return array();
        }

        $spec_cat_id_level = $options[$spec_cat_id]['level'];

        foreach ($options AS $key => $value)
        {
            if ($key != $spec_cat_id)
            {
                unset($options[$key]);
            }
            else
            {
                break;
            }
        }

        $spec_cat_id_array = array();
        foreach ($options AS $key => $value)
        {
            if (($spec_cat_id_level == $value['level'] && $value['recommend_id'] != $spec_cat_id) ||
                ($spec_cat_id_level > $value['level']))
            {
                break;
            }
            else
            {
                $spec_cat_id_array[$key] = $value;
            }
        }
        $cat_options[$spec_cat_id] = $spec_cat_id_array;

        return $spec_cat_id_array;
    }
}


?>